<template>
	<div class="addUpdDaily">
		<div class="title">发布日报</div>
		<div class="center">
			<el-form label-position="top" label-width="80px" :model="formDatas" ref="addDailyRef" id="scrollDiv">
				<div class="formList" v-for="(item, index) in formDatas.dailyReportList">
					<div class="formListCenter" :class="{ centerBorder: index % 2 == 0 }">
						<div class="formListCenterCenter">
							<el-form-item
								label="工作项目"
								:prop="'dailyReportList.' + index + '.projectId'"
								:rules="{ required: true, message: '请选择工作项目', trigger: 'blur' }"
							>
								<el-select v-model="item.projectId" filterable style="width:90%;box-sizing: border-box;" placeholder="请选择工作项目">
									<el-option style="box-sizing: border-box;" v-for="i in projectOptions" :label="i.label" :value="i.value"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item
								label="工作时间"
								:prop="'dailyReportList.' + index + '.workHours'"
								:rules="{ required: true, validator: validatePass, trigger: ['blur', 'change'] }"
							>
								<el-slider v-model="item.workHours" :min="0" :max="24" :step="0.5" style="width:80%;" show-input :show-input-controls="false"></el-slider>
								<div class="gzsjDw">(小时)</div>
							</el-form-item>
							<el-form-item label="工作内容"  :prop="'dailyReportList.' + index + '.content'" :rules="{ required: true, message: '请输入汇报内容', trigger: 'blur' }">
								<div style="border: 1px solid #ccc;width: 100%;height:100%">
									<Toolbar style="border-bottom: 1px solid #ccc" :editor="item.editorRef" :defaultConfig="item.toolbarConfig" :mode="mode" />
									<Editor
										class="editor"
										style="height:260px; overflow-y: auto;"
										v-model="item.content"
										:defaultConfig="editorConfig"
										:mode="mode"
										@onCreated="onCreated"
									/>
								</div>
							</el-form-item>
						</div>
					</div>
					<el-form-item>
						<div class="buttom" v-if="index == formDatas.dailyReportList.length - 1 && formDatas.isRead == 0 ">
							<el-button class="addButton" @click="addItem" >新增项目</el-button>
							<el-button class="removeButton" @click="removeItem(index,item.id)">删除项目</el-button>
							<el-button class="addPublish" @click="pushItem">立即发布</el-button> 
						</div>
						<div class="buttom" v-else-if="index != formDatas.dailyReportList.length - 1 && formDatas.isRead == 0">
							<el-button class="removeButton" @click="removeItem(index,item.id)">删除项目</el-button>
						</div>
					</el-form-item>
				</div>
			</el-form>
			<!-- <div class="buttom" v-if="formDatas.isRead == 0">
				<el-button class="addButton" @click="addItem">新增项目</el-button>
				<el-button class="removeButton" @click="removeItem(item.id)">删除项目</el-button>
				<el-button class="addPublish" @click="pushItem">立即发布</el-button>
			</div> -->
		</div>
	</div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css';
import mydailyStore from '@/store/modules/mydaily';
import useUserStore from '@/store/modules/user';
import { getProjectSelect } from '@/api/hkd';
import { shallowRef,toRaw } from 'vue';
// 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { addDailyReport, editDailyReport, getReportByDate } from '@/api/dailyReport';
import { getToken } from '@/utils/auth';
import { ElMessage, linkEmits } from 'element-plus';
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const useStore = useUserStore();
const store = mydailyStore();

let storeUp = computed(() => {
	let isUp = store.isUp;
	let date = store.date;
	return {
		isUp,
		date
	};
});
let dailyContent = computed(() => {
	return store.dailyContent;
});
let editorIndex = ref(0);
let formData = reactive({
	formDatas: {
		dailyReportList: [
			{
				content: `<p></p>`, //日报内容
				projectId: null, //项目Id
				workHours: Number(0),
				catalogId: null,
				editor: null,
				editorRef: null,
				toolbarConfig: {}
			}
		],
		reportDate: undefined,
		userId: '', //用户id
		isRead: 0
	},
	projectOptions: [],
});
const { formDatas, projectOptions } = toRefs(formData);
const editorConfig = {
	placeholder: '请输入内容...',
	MENU_CONF: {
		uploadImage: {
			server: import.meta.env.VITE_APP_BASE_API + '/common/upload',
			fieldName: 'file',
			metaWithUrl: true,
			headers: {
				Authorization: 'Bearer ' + getToken()
			},
			withCredentials: true,
			timeout: 5 * 1000,
			maxFileSize: 5 * 1024 * 1024,
			allowedFileTypes: ['image/*'],
			onBeforeUpload(file) {
				for (const item in file) {
					if (file[item].size > 5 * 1024 * 1024) {
						ElMessage({ message: '图片大小超过限制，请上传小于5MB的图片', type: 'error', duration: 1 * 1000 });
						return
					}
				}
				return file;
			},
			onSuccess(file, res) {
				console.log(file.name + '上传成功');
			},
			customInsert(res, insertFn) {
				insertFn(res.url, '#', '#');
			},
			onFailed(file, res) {
				ElMessage({ message: file.name + '上传失败' + res, type: 'error', duration: 1 * 1000 });
			},
			onError(file, err, res) {
				if (file.size > 5 * 1024 * 1024) {
					ElMessage({ message: '图片大小超过限制，请上传小于5MB的图片', type: 'error', duration: 1 * 1000 });
				}
			},
		}
	}
};
const mode = 'default';
const userId = ref(useStore.userId);
const dingUserId = ref(useStore.dingUserId);
let isUpdateFlag = ref(false);
const isSy = route.query.isSy;
let delIds = ref([]);
const getProductList = () => {
	getProjectSelect().then(res => {
		if (res.code === 200) {
			projectOptions.value = res.data;
		}
	});
};
const onCreated = (editor) => {
	if (isUpdateFlag) {
		formDatas.value.dailyReportList[editorIndex.value].editorRef = editor;
		editorIndex.value++;
	} else {
		formDatas.value.dailyReportList[formDatas.value.dailyReportList.length - 1].editorRef = editor;
	}
};

const validatePass = (rule, value, callback) => {
	// let num = 0;
	// formDatas.value.dailyReportList.map(item => {
	// 	num += item.workHours;
	// });
	if (value === 0 || !value) {
		callback(new Error('工作时间不能为0'));
	} else {
		callback();
	}
};
const getCatalogId = () => {
	function S4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}
	return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
};
const addItem = () => {
	if (formDatas.value.dailyReportList.length > 0) {
		let sz = formDatas.value.dailyReportList.filter(item => {
			return item.content == '<p></p>';
		});
		if (sz.length > 0) {
			ElMessage({ message: '请输入日报内容', type: 'error', duration: 1 * 1000 });
			return;
		}
	}
	proxy.$refs['addDailyRef'].validate(valid => {
		if (valid) {
			// let num = 0;
			// formDatas.value.dailyReportList.map(item => {
			//     num += item.workHours;
			// })
			// let workHours = 7.5 - num;

			let form = {
				content: `<p></p>`, //日报内容
				projectId: undefined, //项目Id
				workHours: Number(0),
				catalogId: getCatalogId(),
				reportDate: new Date(),
				editorRef: null,
				toolbarConfig: {}
			};
			formDatas.value.dailyReportList.push(form);
			proxy.$nextTick(() => {
				let container = proxy.$el.querySelector('#scrollDiv');
				container.scrollTop = container.scrollHeight;
			});
		}
	});
};
const removeItem = (index,delId) => {
	let list = formDatas.value.dailyReportList;
	if (list.length > 1) {
		let editor = list[list.length - 1].editorRef;
		if (editor == null) return;
		editor.destroy();
		list.splice(index,1);
		editorIndex.value--;
	}
	if (delId) {
		delIds.value.push(delId);
	}
	proxy.$nextTick(() => {
		let container = proxy.$el.querySelector('#scrollDiv');
		container.scrollTop = container.scrollHeight;
	});
};
const getAlldata = data => {
	let param = {
		date: data
	};
	getReportByDate(param).then(res => {
		if (res.code === 200) {
			if (res.data) {
				formDatas.value = res.data;
				if (res.data.dailyReportList.length > 0) {
					res.data.dailyReportList.map((item, index) => {
						formDatas.value.dailyReportList[index].editorRef = null;
						formDatas.value.dailyReportList[index].toolbarConfig = {};
						formDatas.value.dailyReportList[index].content = getImgSrc(formDatas.value.dailyReportList[index].content);
					});
				}
			}
		}
	});
};
const getImgSrc = richtext => {
	if (richtext.indexOf('src="') != -1) {
		if (richtext.indexOf('http') != -1 || richtext.indexOf('https') != -1) {
			return richtext;
		}
		richtext = richtext.replaceAll('src="', 'src="' + import.meta.env.VITE_APP_BASE_API + '');
	}
	return richtext;
};
const isActive = r => {
	return r.path === route.path;
};
const toLastView = (visitedViews, view) => {
	const latestView = visitedViews.filter(item => {
		return item.path == '/daily/mydaily';
	});
	if (latestView[0]) {
		router.push(latestView[0].fullPath);
	} else {
		// now the default is to redirect to the home page if there is no tags-view,
		// you can adjust it according to your needs.
		router.replace({ path: view.fullPath });
		router.push({path:'/daily/mydaily'})
	}
};
const objDeepCopy = (source) =>{
	let sourceCopy = source instanceof Array ? [] : {};
	for (let item in source) {
		sourceCopy[item] = typeof source[item] === 'object' ? objDeepCopy(source[item]) : source[item];
	}
	return sourceCopy;
}
const pushItem = () => {
	if (formDatas.value.dailyReportList.length > 0) {
		let sz = formDatas.value.dailyReportList.filter(item => {
			console.log(item.content);
			return item.content == '<p></p>';
		});
		if (sz.length > 0) {
			ElMessage({ message: '请输入日报内容', type: 'error', duration: 1 * 1000 });
			return;
		}
	}
	proxy.$refs['addDailyRef'].validate(valid => {
		if (valid) {
			let oldForm = toRaw(formDatas.value);
			let dailyReportList = [];
			let form = {
				reportDate: storeUp.value.date ? storeUp.value.date : proxy.parseTime(new Date(), '{y}-{m}-{d}'),
				userId: userId.value,
				id: oldForm.id ? oldForm.id : null,
			}
			if (delIds.value) {
				form.delIds = delIds.value.join(',');
			}
			if (oldForm.dailyReportList.length > 0) {
				oldForm.dailyReportList.map(item => {
					let list = {};
					list.content = item.content;
					if (item.content.indexOf(import.meta.env.VITE_APP_BASE_API) != -1) {
						list.content = item.content.split(import.meta.env.VITE_APP_BASE_API).join('');
					} else if (item.content.indexOf(import.meta.env.VITE_APP_BASE_URL) != -1) {
						list.content = item.content.split(import.meta.env.VITE_APP_BASE_URL).join('');
					}
					list.projectId = item.projectId;
					list.workHours = item.workHours;
					list.catalogId = item.catalogId;
					list.reportDate = item.reportDate;
					list.id = item.id ? item.id : null; 
					dailyReportList.push(list);
				});
				form.dailyReportList = dailyReportList;
				//formDatas.value.dailyReportList = toRaw(formDatas.value.dailyReportList);
			}
			
			if (oldForm.id) {
				editDailyReport(form).then(res => {
					if (res.code == 200) {
						proxy.$modal.msgSuccess('修改成功');
						clearEditor();
						proxy.$nextTick(() => {
							proxy.$tab.closePage(route).then(({ visitedViews }) => {
								if (isActive(route)) {
									toLastView(visitedViews, route);
								}
							});
						});
					}
				});
			} else {
				addDailyReport(form).then(res => {
					if (res.code == 200) {
						proxy.$modal.msgSuccess('新增成功');
						clearEditor();
						proxy.$nextTick(() => {
							proxy.$tab.closePage(route).then(({ visitedViews }) => {
								if (isActive(route)) {
									toLastView(visitedViews, route);
								}
							});
						});
					}
				});
			}
		}
		//console.log(valid);
	});
};
const clearEditor = () => {
	let list = formDatas.value.dailyReportList;
	if (list.length > 0) {
		list.map(item => {
			const editor = item.editorRef;
			if (editor == null) return;
			editor.destroy();
		});
		editorIndex.value = 0;
	}
};
onBeforeUnmount(() => {
	clearEditor();
});
watch(
	storeUp,
	(newV, oldV) => {
		if (newV.isUp) {
			isUpdateFlag.value = true;
			getAlldata(newV.date);
		}
	},
	{ immediate: true }
);
getProductList();
if (isSy) {
	getAlldata(proxy.parseTime(new Date(), '{y}-{m}-{d}'));
}
</script>

<style lang="scss" scoped>
$fontSize: 14px;
$color: #be1a21;
$display: flex;
$alignItems: center;
$justifyContent: center;
.addUpdDaily {
	width: 100%;
	height: 100%;
	background-color: #fff;
	padding: 2vw 5vh;
	border-radius: 10px;
	.title {
		width: 159px;
		height: 32px;
		background: url('../../assets/images/spbj.png') center center no-repeat;
		background-size: 100% auto;
		color: $color;
		display: $display;
		align-items: $alignItems;
		padding-left: 10px;
	}
	.center {
		width: 100%;
		height: 100%;

		.el-form {
			width: 100%;
			height: calc(100% - 50px) ;
			display: flex;
			flex-flow: wrap;
			overflow-y: auto;
			.formList {
				width: 45%;
				//height: 100%;
				margin-right: 64px;
				min-height: 600px;
				.formListCenter {
					width: 100%;
					//height: 80%;
					.formListCenterCenter {
						width: 90%;
						margin-top: 30px;
					}
					.gzsjDw {
						width: 10%;
						margin: 0 auto;
					}
				}
				.centerBorder {
					border-right: 1px dashed #d9d9d9;
				}
				.buttom {
					width: 90%;
					height: 10%;
					position: relative;
					bottom: 0px;
					left: 0px;
					.addButton {
						background: #ffdade;
						border-color: #ffdade;
						color: $color;
					}
					.removeButton {
						background: #eeeeee;
						border-color: #eeeeee;
						color: #999999;
					}
					.addPublish {
						background: $color;
						border-color: $color;
						color: #ffffff;
					}
				}
			}
		}
	}
}
.buttom {
	margin-top: 20px;
	text-align: center;
	
	// width: 90%;
	// height: 10%;
	// display: $display;
	// justify-content: $justifyContent;
	// align-items: $alignItems;
	.addButton {
		background: #ffdade;
		border-color: #ffdade;
		color: $color;
	}
	.removeButton {
		background: #eeeeee;
		border-color: #eeeeee;
		color: #999999;
	}
	.addPublish {
		background: $color;
		border-color: $color;
		color: #ffffff;
	}
}

.el-select__popper {
	width: 90%;
}
.el-slider {
	flex-direction: row-reverse;
}
:deep(.el-slider__runway.show-input) {
	margin-right: 0px !important;
	margin-left: 30px !important;
}
$primary-color: #041428;
.el-form::-webkit-scrollbar,
.w-e-text-container::-webkit-scrollbar {
	width: 10px;
	height: 300px;
}
.el-form::-webkit-scrollbar-thumb,
.w-e-text-container::-webkit-scrollbar-thumb {
	border-radius: 10px;
	-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
	opacity: 0.2;
	background: fade($primary-color, 70%);
}

.el-form::-webkit-scrollbar-track,
.w-e-text-container::-webkit-scrollbar-track {
	-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
	border-radius: 10px;
	background: fade($primary-color, 30%);
	margin-top: 15px;
}
</style>
